﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YuanRegression.Models
{

    /// <summary>
    /// 回归模型数据
    /// </summary>
    public class RegressionModel
    {
        #region 属性
        /// <summary>
        /// X序列
        /// </summary>
        public List<double> X { get; set; }

        /// <summary>
        /// Y序列
        /// </summary>
        public List<double> Y { get; set; }  // grama sugar
        
        /// <summary>
        /// X的平均值 LINQ写法
        /// </summary>
        public double AvgX => X==null||X.Count()==0 ? 0: X.Average();    //property

        /// <summary>
        /// Y的平均值
        /// </summary>
        public double AvgY => Y==null||Y.Count()==0 ? 0 : Y.Average();

        /// <summary>
        /// x序列（Xi-AvgX)
        /// </summary>
        private List<double> x => X == null || X.Count() == 0 ? new List<double>() : X.Select(m=>m-AvgX).ToList();

        /// <summary>
        /// y序列
        /// </summary>
        private List<double> y => Y == null || Y.Count() == 0 ? new List<double>() : Y.Select(m => m - AvgY).ToList();

        /// <summary>
        /// 需要计算的系数a
        /// </summary>
        private double a { get; set; }

        /// <summary>
        /// 需要计算的系数b
        /// </summary>
        private double b { get; set; }

        /// <summary>
        /// 计算参数a和b
        /// </summary>

        #endregion
        public void Compute()
        {
            double answer1 = 0;
            double answer2 = 0;
            for(int i = 0; i < X.Count; i++)
            {
                answer1 += x[i] * y[i];
                answer2 += x[i] * x[i];
            }
            b = answer1 / answer2;
            a = AvgY - b * AvgX;
        }

        /// <summary>
        /// 预测函数
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public double Forecast(double x)
        {
            return a + b * x;
        }
    }

    
}
